package com.ifast.hessian.config;

import java.io.IOException;
import java.util.Base64;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.remoting.caucho.HessianServiceExporter;

import com.ifast.hessian.service.CheckFaceService;

/**
 * <用于配置发布hessian接口> <这里只是做了最简单的配置，还可以设置超时时间，密码这些安全参数>
 * 
 * @author wzh
 * @version 2018-11-18 16:55
 * @see [相关类/方法] (可选)
 **/
@Configuration
public class HessionServiceConfig{

	
	@Autowired
	private CheckFaceService  dBCheckFaceService;
	
	private static String serverAuth = "Basic " +Base64.getEncoder().encodeToString("face:face".getBytes());
	
	@Bean("/hessian/check.do")
	public HessianServiceExporter checkFace() {
		HessianServiceExporter exporter = new HessianServiceExporter(){

			@Override
			public void handleRequest(HttpServletRequest request, HttpServletResponse response)
					throws ServletException, IOException{ 
				String authorization = request.getHeader("Authorization");  
				
				//basicAuth
				if(StringUtils.isBlank(authorization)){
					response.setStatus(403);
					return;
				}
				if(!serverAuth.equals(authorization.trim())){
					response.setStatus(403);
					return;
					//throw new ServletException("Timestamp is timeout");
				}
				
				super.handleRequest(request, response);
			}
			 
		};
		exporter.setService(dBCheckFaceService);
		exporter.setServiceInterface(CheckFaceService.class);
		return exporter;
	}
	
}